﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using Think9.Models;

namespace Think9.Controllers.Basic
{
    public class PictureController : Controller
    {
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        ///
        [HttpPost]
        public ActionResult Uplaod(List<IFormFile> file)
        {
            DataResult<string> rtnResult = new DataResult<string>();

            foreach (var formFile in file)
            {
                if (formFile.Length > 0)
                {
                    FileInfo fi = new FileInfo(formFile.FileName);
                    string ext = fi.Extension;
                    var orgFileName = fi.Name;
                    //var newFileName = Guid.NewGuid() + ext;
                    var newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + formFile.FileName;

                    var uploads = Path.Combine(Directory.GetCurrentDirectory(), "Resource");
                    var filePath = Path.Combine(uploads, newFileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        //await formFile.CopyToAsync(stream);
                    }
                    rtnResult.IsSuccess = true;
                }
                else
                {
                    rtnResult.ErrorMessage = "上传文件出错!";
                }
            }
            return Json(rtnResult);
        }

        //public ActionResult UploadImg(string Parm1, string Parm2)
        //{
        //    if (Request.Files.Count > 0)
        //    {
        //        //p1,p2没什么用，只是为了证明前端中额外参数data{parm1,parm2}成功传到后台了
        //        string p1 = Parm1;
        //        string p2 = Parm2;
        //        //获取后缀名
        //        string ext = Path.GetExtension(Request.Files[0].FileName);
        //        //获取/upload/文件夹的物理路径
        //        string mapPath = Server.MapPath(Request.ApplicationPath);
        //        //通过上传时间来创建文件夹，每天的放在一个文件夹中
        //        string dir = mapPath + "upload/" + DateTime.Now.ToString("yyyy-MM-dd");
        //        DirectoryInfo dirInfo = Directory.CreateDirectory(dir);
        //        //在服务器存储文件，文件名为一个GUID
        //        string fullPath = dir + "/" + Guid.NewGuid().ToString() + ext;
        //        Request.Files[0].SaveAs(fullPath);
        //        //获取图片的相对路径
        //        string imgSrc = fullPath.Replace(mapPath, "/");
        //        return Json(new { IsSuccess = 1, Msg = "上传成功", Src = imgSrc });
        //    }
        //    else
        //    {
        //        return Json(new { IsSuccess = 0, Msg = "上传失败", Src = "" });
        //    }
        //}
    }
}